/**
 * Created by z30 on 15-6-7.
 */

var logger      = require('./log.js').logger;
var http        = require('http');
var me          = require('./acc');
var crypto      = require('crypto');
var reqbodyaes  = require('./t');
var qs          = require('querystring');
var redisconf   = require('../conf/config')['redis']['default'];
var redis       = require('redis');
const secret = 'vmsl239xcvsdf.+23';



exports.ViewRawBody=function(req,res,next){
    logger.debug(req.body);
    next()
};

/**
 * WashCipherBody express 中间件来过滤疑似加密字符串
 *
 * @param {object} req
 * @param {object} res
 * @param {object} next
 * @api public
 */
exports.WashCipherBody=function(req,res,next){
    logger.debug('WASH HEADER'+req.headers['x-forwarded-for']||req.connection.remoteAddress);
    logger.debug(req.headers);
    logger.debug(typeof(req.body));
   // console.log(req)

    if(typeof(req.body)=="string" && req.body.length>0)
    {
        logger.debug(req.body);
       // console.log(req.body)

        reqbodyaes.decodeCipher_cb(req.body,function(washbody,err){
            if(err)
            {
                logger.debug('错误的字符串:'+err.message);
                res.status(400).end(JSON.stringify({res:-1,error_info:"错误的请求格式"}))
            } else
            {
                try {
                    req.body=JSON.parse(washbody);
                    req.body['cryflag']=1; //有加密
                   // console.log(req.body)
                    next();
                }catch(e){
                    logger.debug('WASH '+washbody);
                    logger.debug('WASH '+'错误的BODY解析:'+err.message);
                    res.status(400).end(JSON.stringify({res:-1,error_info:"错误的请求格式解析"}))
                }
            }
        });
    } else
    {
       // console.log(req.body);
        req.body['cryflag']=0;  //没有加密
        next()
    }
};

/**
 * DeepCopy Javascript的深拷贝
 *
 * @param {object} source
 * @return {object} ind_object
 * @api public
 */

exports.DeepCopy=function(source) {
    var result={};
    for (var key in source) {
        result[key] = typeof source[key]==='object'? deepCoyp(source[key]): source[key];
    }
    return result;
};

//JSON添加
exports.Jsadd=function extend(des, src, override){
    if(src instanceof Array){
        for(var i = 0, len = src.length; i < len; i++)
            extend(des, src[i], override);
    }
    for( var i in src){
        if(override || !(i in des)){
            des[i] = src[i];
        }
    }
    return des;
};


/**
 * 将数据库返回的配置信息转换为MAP
 *
 * @param {object} 目标MAP
 * @param {object} 源MAP
 * @api public
 */
exports.G_JSON=function extend(des, src){
    des={};
    //console.log(src);
    for(var i = 0, len = src.length; i < len; i++)
      des[src[i].id] = src[i].name;
        //console.log(src[i]);
    /*
        if (src[i].id=='pd_llsms_restnum'||src[i].id=='pd_llsms_switch')
        {
            des[src[i].id] = parseInt((src[i].name));
        } else {

        }
        */
    // console.log(des);
    return des;
};

/*
 * 将数据库返回的配置信息转换为MAP,NAME和ID做了颠倒
 *
 * @param {object} 目标MAP
 * @param {object} 源MAP
 * @api public

 */
exports.G_JSON_R=function extend(des, src){
    des={};
    //console.log(src);
    for(var i = 0, len = src.length; i < len; i++)
        //console.log(src[i]);
        des[src[i].name]=src[i].id;
    // console.log(des);
    return des;
};


//�ж������ƶ��ַ��ظ�����
exports.G_ARRAY_IF=function(arr,xstr){
    var n=0;
    for(var i=0,len=arr.length;i<len;i++)
        if (arr[i]==xstr) n++;
    return n;
};
//�ж�������K-V��V���ƶ��ַ��ظ�����
exports.G_ARRAY_KV_IF=function(arr,delimer,xstr){
    var n=0;
    for(var i=0,len=arr.length;i<len;i++)
    {  if ((arr[i].split(delimer))[1]==xstr) n++;}
    return n;
};
/*�Զ����ܣ�ͳһ��ѯDB
 * ���Ӵ���SQL�����صļ�¼����CB
 *
 */
exports.Gen_DB=function(p_conn,p_sql,p_rec_num,callback){
    p_conn.query(p_sql,function (err, sqlres) {
        if (err) {
            p_conn.release();
            logger.debug(err.message);
            callback(err);
        } else
        {
            p_conn.release();
            (p_rec_num==1) ? callback(sqlres[0]) : callback(sqlres);
        }
    });
};
//JS ȥ������
exports.getNoRepeat=function (s_arr) {
    return s_arr.sort().join(",,").replace(/(,|^)([^,]+)(,,\2)+(,|$)/g,"$1$2$4").replace(/,,+/g,",").replace(/,$/,"").split(",");
};

//���������ݷ��س�html select optgroup �ĸ�ʽ
exports.ConvToGroup=function(p_arr,p_title,callback){
    var arr_new=[];
    for(var i=0;i<p_arr.length;i++)
    {
        var obj={};
        obj['text']=p_title+p_arr[i].ulevel;
        obj['children']=[];
        for(var j=0;j<p_arr[i].text.split(',').length;j++)
        {
            var obj_inner={};
            obj_inner['id']=p_arr[i].text.split(',')[j];
            obj_inner['text']=p_arr[i].text.split(',')[j];
            obj['children'].push(obj_inner)
        }
        arr_new.push(obj)
    }
    //  console.log(arr_new);
    callback(arr_new);
};

/*
    MD5 转换函数
 */
exports.md5 = function (str) {
    var md5sum = crypto.createHash('md5');
    md5sum.update(str);
    str = md5sum.digest('hex');
    return str;
};

exports.randomString = function (size) {
    size = size || 6;
    var code_string = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
    var max_num = code_string.length + 1;
    var new_pass = '';
    while (size > 0) {
        new_pass += code_string.charAt(Math.floor(Math.random() * max_num));
        size --;
    }
    return new_pass;
};

exports.randomString_cb = function (size,cb) {
    size = size || 6;
    var code_string = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
    var max_num = code_string.length + 1;
    var new_pass = '';
    while (size > 0) {
        new_pass += code_string.charAt(Math.floor(Math.random() * max_num));
        size --;
    }
    cb(new_pass);
};
/*
 @param string like '$$,YL1,YC1006,YH1,YC1018,YH2,YC1002'
 */
exports.washchildreninfo = function (children,tuijian) {
    logger.debug(children);
    var list_children=children.split(',');
    var lv2=0;
    var lv3=0;
    for (var i=2;i<list_children.length;i++)
    {

        if(list_children[i].substr(0,2)=='YH')
           {
               lv2++;
           }
            if(list_children[i].substr(0,2)=='YC') {
                lv3++;
            }
    }
    return {
        'lv2':lv2,
        'lv3':lv3,
        'tuijian':tuijian
    }
};

//获取文件名
exports.getFNameBefore=function(fname){
    var result =/\.[^\.]+/.exec(fname);
    return fname.split(result)[0]
};

//SHA256-hmac带秘钥
exports.sha256_hmac=function(fstr){
    return crypto.createHmac('sha256', secret).update(fstr).digest('hex');
};

//SHA512-hmac带秘钥
exports.sha512_hmac=function(fstr){
    return crypto.createHmac('sha512', secret).update(fstr).digest('hex');
};

//SHA256-STD
exports.sha256=function(fstr){
    var hash = crypto.createHash('sha256');
    return hash.update(fstr).digest('hex');
};


// get请求
exports.http_Get=function(data,hostName,port,path){

    var content = qs.stringify(data);
    var options = {
        hostname: hostName,
        port: port,
        path: path +'?' + content,
        method: 'GET'
    };

    var req = http.request(options, function (res) {
        logger.debug('STATUS: ' + res.statusCode);
        logger.debug('HEADERS: ' + JSON.stringify(res.headers));

        res.setEncoding('utf8');
        res.on('data', function (chunk) {
            logger.debug('BODY: ' + chunk);
        });
    });

    req.on('error', function (e) {
        logger.debug('problem with request: ' + e.message);
    });
    req.end();

}

//redis 存
exports.redisSave = function (key,values,cb) {
    var client = redis.createClient(redisconf.port,redisconf.host);
    if(redisconf.password){
        client.auth(redisconf.password);
    }
    client.select(redisconf.db,function (err) {
        if(err){
            logger.error(err);
            cb(err,null)
        }else {
            client.set(key,values,function (error,res) {
                if(error){
                    logger.error(error);
                    cb(error,null)
                }else {
                    logger.debug("redis-set,key:"+key+",value:"+values);
                    cb(null,res)
                }

                client.end(true);
            })
        }
    })
}

//redis 取
exports.redisGet = function (key,cb) {
    var client = redis.createClient(redisconf.port,redisconf.host);
    if(redisconf.password){
        client.auth(redisconf.password);
    }
    client.select(redisconf.db, function(error){
        if(error) {
            logger.error(err);
            cb(error,null)
        } else {
            // get
            client.get(key, function(error, res){
                if(error) {
                    logger.error(err);
                    cb(error,null)
                } else {
                    logger.debug("redis-get,key:"+key+",value:"+res);
                    cb(null,res)
                }

                // 关闭链接
                client.end(true);
            });
        }
    });
}
